package com.jhd.jiangxi.activity.scan.in.returns;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.activity.scan.BillFragment;
import com.jhd.jiangxi.activity.scan.ContentFragment;
import com.jhd.jiangxi.activity.scan.DetailActivity;
import com.jhd.jiangxi.activity.scan.in.purchase.PurchaseActivity;
import com.jhd.jiangxi.activity.scan.in.scrap.ScrapInActivity;
import com.jhd.jiangxi.entity.LastInputEditText;
import com.jhd.jiangxi.util.DeptChoose;
import com.jhd.jiangxi.util.PopWindow;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.util.VaccineContain;
import com.jhd.jiangxi.vo.DeliveryDtl;
import com.jhd.jiangxi.vo.ElectCodePackageVo;
import com.jhd.jiangxi.vo.ElectCodePackageVoList;
import com.jhd.jiangxi.vo.GlobalDictionary;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.PurchaseReceiptDtlVo;
import com.jhd.jiangxi.vo.PurchaseReceiptMstVo;
import com.jhd.jiangxi.vo.PurchaseReturn;
import com.jhd.jiangxi.vo.RefDept;
import com.jhd.jiangxi.vo.VaccineCount;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.jiangxi.activity.scan.in.supply.SupplyActivity.electCodePackageVos2;

/*退货入库*/
public class ReturnInActivity extends BaseActivity implements View.OnClickListener {
    private ViewPager vp;
    private BillFragment billFragment;
    private ContentFragment contentFragment;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private String[] categoryName = {"国家免疫规划疫苗", "地方免疫规划疫苗", "应急接种疫苗", "非免疫规划疫苗", "群体性预防接种疫苗", "紧急使用疫苗"};
    private String[] categoryId = {"1", "4", "5", "2", "6", "7"};
    private FragmentPagerAdapter adapter;
    private BarcodeDataReceiver barcodeDataReceiver;
    private AlertDialog _alertDialog = null;
    private final List<String> id = new ArrayList<String>();
    private final List<String> name = new ArrayList<String>();
    private final List<String> deptId = new ArrayList<String>();
    private final List<String> deptName = new ArrayList<String>();
    private final List<String> category = new ArrayList<String>();
    private final List<String> orderNo = new ArrayList<String>();
    private final List<String> sourceType = new ArrayList<String>();
    private final List<String> createTime = new ArrayList<String>();
    private final List<String> sourceId = new ArrayList<String>();
    private final List<String> transformUnit = new ArrayList<String>();
    private final List<String> transformUnitName = new ArrayList<String>();
    List<VaccineCount> vaccineCountList = new ArrayList<>();
    private RecyclerView rvVaccine;
    private Context context = ReturnInActivity.this;
    private LastInputEditText btnOutDept;
    private TextView btnApprovalIn, btnVaccineType, btnPriceBook,btnDeliveryDept,btnEndTime,btnStartTime, btnToTemp,btnTransportEquip, btnStorage, btnSourceType_0, btnSourceType, btnOrderNo;//bill界面:审批人,供货单位,疫苗类型,价格本,下一步
    private Button btnSubmitVaccine, btnDelAllVaccine, btnCountVaccine;//content界面:提交,清空,入库明细
    private PopupWindow popup;
    private ListView listView;
    private List<PurchaseReturn> purchaseReturnList;
    protected static ArrayList<PiatsInfo> piatsInfos2 = new ArrayList<>();//单号中的疫苗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_in);
        popup= new PopupWindow(context);;
        openScan(context);
        initView();
        initEvent();
    }

    /*将顶部标题带入,新建俩个fragment*/
    private void initView() {
        initHeader("退货入库");
        vp = (ViewPager) findViewById(R.id.vpSheet);
        billFragment = new BillFragment();
        contentFragment = new ContentFragment();
        mDatas.add(billFragment);
        mDatas.add(contentFragment);
        tabs = findViewById(R.id.tabSheet);
    }

    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        btnSourceType_0 = (TextView) view.findViewById(R.id.btnSourceType_0);
        btnSourceType = (TextView) view.findViewById(R.id.btnSourceType);
        btnOrderNo = (TextView) view.findViewById(R.id.btnOrderNo);
        btnApprovalIn = (TextView) view.findViewById(R.id.btnApprovalIn);
        btnOutDept = (LastInputEditText) view.findViewById(R.id.btnOutDept);
        btnVaccineType = (TextView) view.findViewById(R.id.btnVaccineType);
        btnStartTime = (TextView) view.findViewById(R.id.btnStartTime);
        btnEndTime = (TextView) view.findViewById(R.id.btnEndTime);
        btnPriceBook = (TextView) view.findViewById(R.id.btnPriceBook);
        btnDeliveryDept = (TextView) view.findViewById(R.id.btnDeliveryDept);
        btnToTemp = (TextView) view.findViewById(R.id.btnToTemp);
        btnStorage = (TextView) view.findViewById(R.id.btnStorage);
        btnTransportEquip = (TextView) view.findViewById(R.id.btnTransportEquip);
        btnApprovalIn.setOnClickListener((View.OnClickListener) context);
//        btnOutDept.setOnClickListener((View.OnClickListener) context);
        btnVaccineType.setOnClickListener((View.OnClickListener) context);
        btnPriceBook.setOnClickListener((View.OnClickListener) context);
        btnToTemp.setOnClickListener((View.OnClickListener) context);
        btnStorage.setOnClickListener((View.OnClickListener) context);
        btnOrderNo.setOnClickListener((View.OnClickListener) context);
        btnStartTime.setOnClickListener((View.OnClickListener) context);
        btnEndTime.setOnClickListener((View.OnClickListener) context);
        btnTransportEquip.setOnClickListener((View.OnClickListener) context);
        btnDeliveryDept.setOnClickListener((View.OnClickListener) context);
        btnSourceType_0.setVisibility(View.GONE);//将默认自制单据的隐藏
        btnSourceType.setVisibility(View.GONE);//只有单号退货
        btnSourceType.setText("下级退货单");
        btnOrderNo.setVisibility(View.VISIBLE);//只有单号退货
        getSubordinatePurchaseReturnList();//获取订单号的列表
        getApproval(btnApprovalIn, "退货入库");//获取审批人列表
        getDept();//获取退货单位，institutionalType=2
        getVaccineDistributionDempartByDeptId();//获取发货单位列表
        getGlobalDictionaryByType("冷链设备类型");//获取运输设备
        getPriceBookMst();//获取价格本列表
        getStorageInfoList();//获取储位列表
        btnOutDept.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name.clear();id.clear();
                if(deptList!=null&&isCheck==false){
                    for (RefDept refDept : deptList) {
                        if(refDept.getName().contains(btnOutDept.getText().toString())&&"2".equals(refDept.getInstitutionalType())){
                            name.add(refDept.getName());
                            id.add(refDept.getId());
                        }
                    }
                    PopWindow.show(application, context,popup,isCheck, btnOutDept, name, id, 1);
                }
            }
        });
        btnOutDept.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    name.clear();id.clear();
                    if (deptList != null) {
                        for (RefDept refDept : deptList) {
                            if(refDept.getName().contains(btnOutDept.getText().toString())&&"2".equals(refDept.getInstitutionalType())){
                                name.add(refDept.getName());
                                id.add(refDept.getId());
                            }
                        }
                        PopWindow.show(application, context,popup,isCheck, btnOutDept, name, id, 1);
                    }
                }
                return false;
            }
        });
        btnDeliveryDept.setOnClickListener((View.OnClickListener) context);
        btnDeliveryDept .addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name.clear();id.clear();
                if(deptList2!=null&&isCheck==false){
                    for (RefDept refDept : deptList2) {
                        if(refDept.getName().contains(btnDeliveryDept.getText().toString())){
                            name.add(refDept.getName());
                            id.add(refDept.getId());
                        }
                    }
                    PopWindow.show(application, context,popup,isCheck, btnDeliveryDept, name, id, 7);
                }
            }
        });
        btnDeliveryDept.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    name.clear();id.clear();
                    if (deptList2 != null) {
                        for (RefDept refDept : deptList2) {
                            if(refDept.getName().contains(btnDeliveryDept.getText().toString())){
                                name.add(refDept.getName());
                                id.add(refDept.getId());
                            }
                        }
                        PopWindow.show(application, context,popup,isCheck, btnDeliveryDept, name, id, 7);
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        btnSubmitVaccine = (Button) view.findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine = (Button) view.findViewById(R.id.btnDelAllVaccine);
        btnCountVaccine = (Button) view.findViewById(R.id.btnCountVaccine);
        rvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvVaccine.setLayoutManager(layoutManager);
        btnSubmitVaccine.setOnClickListener((View.OnClickListener) context);
        btnDelAllVaccine.setOnClickListener((View.OnClickListener) context);
        btnCountVaccine.setOnClickListener((View.OnClickListener) context);
    }

    /*点击下一步或者点击扫码入库之前的判断*/
    private void setBtnToTemp() {
        if (btnSourceType.getText().toString().equals("来源类型") || btnApprovalIn.getText().toString().equals("审核人") || btnOutDept.getText().toString().equals("")
                || btnVaccineType.getText().toString().equals("疫苗属性") || btnPriceBook.getText().toString().equals("价格本") ||
                btnStorage.getText().toString().equals("储位")||btnTransportEquip.getText().toString().equals("运输设备")) {
            UtilHelper.alertMsg(context, "请配置好单据页面", "点击任意处关闭弹窗");
            vp.setCurrentItem(0);
        } else {
            if(btnSourceType.getText().toString().equals("自制单据")&&!DeptChoose.isContain(deptList,btnOutDept.getText().toString())){
                UtilHelper.alertMsg(ReturnInActivity.this, "请选择正确的出货单位", "点击任意处关闭弹窗");
                vp.setCurrentItem(0);
            }else{
                if(application.getStorageId().equals(application.getStorageId2())){
                    if(btnSourceType.getText().toString().equals(application.getCheckType())) {//说明来源没变
                        if (btnOrderNo.getVisibility() == View.VISIBLE) {
                            if (btnOrderNo.getText().toString().equals("单号")) {
                                UtilHelper.alertMsg(context, "请选择下级退货单号", "点击任意处关闭弹窗");
                            } else {
                                if (application.getOrderNoId().equals(application.getOrderNoId2())) {
                                    vp.setCurrentItem(1);
                                    ScanUtil.powerOnScan(context);
                                } else {
                                    if (piatsInfos.size() > 0) {
                                        vp.setCurrentItem(0);
                                        isClearDialog("单号已经重选,",0);
                                    } else {
                                        application.setOrderNoId2(application.getOrderNoId());
                                        vp.setCurrentItem(1);
                                        ScanUtil.powerOnScan(context);
                                    }
                                }
                            }
                        }else{
                            if(application.getCategory().equals(application.getCheckVaccineType())&&application.getSaleDeptId().equals(application.getSaleDeptId2())){
                                vp.setCurrentItem(1);
                                ScanUtil.powerOnScan(context);
                            }else{
                                if(piatsInfos.size()>0){
                                    vp.setCurrentItem(0);
                                    isClearDialog("疫苗属性或者出货单位已经重选,",1);
                                }else{
                                    application.setCheckVaccineType(application.getCategory());
                                    application.setSaleDeptId2(application.getSaleDeptId());
                                    vp.setCurrentItem(1);
                                    ScanUtil.powerOnScan(context);
                                }
                            }
                        }
                    }else{
                        if(piatsInfos.size()>0){
                            vp.setCurrentItem(0);
                            isClearDialog("来源类型已经重选,",2);
                        }else{
                            application.setCheckType(btnSourceType.getText().toString());
                            application.setSaleDeptId2(application.getSaleDeptId());
                            application.setOrderNoId2(application.getOrderNoId());
                            application.setCheckVaccineType(application.getCategory());
                            vp.setCurrentItem(1);
                            ScanUtil.powerOnScan(context);
                        }
                    }
                }else{
                    if(piatsInfos.size()>0){
                        vp.setCurrentItem(0);
                        isClearDialog("储位已经重选,",3);
                    }else{
                        application.setCheckType(btnSourceType.getText().toString());
                        application.setSaleDeptId2(application.getSaleDeptId());
                        application.setOrderNoId2(application.getOrderNoId());
                        application.setCheckVaccineType(application.getCategory());
                        vp.setCurrentItem(1);
                        ScanUtil.powerOnScan(context);
                    }
                }
            }
        }
    }

    public void isClearDialog(String title,int position) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle("退货入库");
        alertBuilder.setMessage(title+"将会对之前的扫描进行清空,您确定吗?");
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(position==0){
                    application.setOrderNoId2(application.getOrderNoId());
                }else if(position==1){
                    application.setCheckVaccineType(application.getCategory());
                    application.setSaleDeptId2(application.getSaleDeptId());
                }else if(position==2){
                    application.setCheckType(btnSourceType.getText().toString());
                }else if(position==3){
                    application.setCheckType(btnSourceType.getText().toString());
                    application.setCheckVaccineType(application.getCategory());
                    application.setSaleDeptId2(application.getSaleDeptId());
                    application.setOrderNoId2(application.getOrderNoId());
                }
                piatsInfos.clear();
                RecyclerAdapter recyclerAdapter = new RecyclerAdapter(piatsInfos);
                rvVaccine.setAdapter(recyclerAdapter);
                vp.setCurrentItem(1);
                ScanUtil.powerOnScan(context);
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }


    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
                if (tab.getPosition() == 1) {
                    setBtnToTemp();
                } else {
                    ScanUtil.powerOffScan(context);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        TabLayout.Tab tab = tabs.getTabAt(0);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_left);
        tab.setText("交货单");
        tab = tabs.getTabAt(1);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_right);
        tab.setText("扫码入库");
    }

    public void openScan(Context context) {
        barcodeDataReceiver = new BarcodeDataReceiver();
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        context.registerReceiver(barcodeDataReceiver, mFilter);
        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
        mIntent.putExtra("SCAN_INTERVAL", Long.valueOf(3000));
        mIntent.putExtra("EXTRA_TRIG_MODE", 0);// 0 配置扫描头为普通触发模式 /1 配置扫描头为连续扫描模式 /2 配置扫描头为超时扫描模式*
        mIntent.putExtra("EXTRA_SCAN_MODE", 3);// 1 ：直接填充模式* /2 ：虚拟按键模式 /3 ：广播输出模式
        context.sendBroadcast(mIntent);
        Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
        mIntent2.putExtra("EXTRA_SCAN_NOTY_SND", 1);
        mIntent2.putExtra("EXTRA_SCAN_NOTY_VIB", 1);
        sendBroadcast(mIntent2);
    }

    public void closeScan(Context context) {
        context.unregisterReceiver(barcodeDataReceiver);
    }

    class BarcodeDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
            final String scanStatus = intent.getStringExtra("SCAN_STATE");
            Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
            context.sendBroadcast(stopIntent);
            if ("ok".equals(scanStatus)) {
                if (btnSourceType.getText().toString().equals("自制单据")) {
                    getVaccineInfoByCodeSingle(scanResult_1, "4",3, rvVaccine);//index为orderType的值
                } else if (btnSourceType.getText().toString().equals("下级退货单")) {
                    PiatsInfo sPiatsInfo = new PiatsInfo();
                    for (PiatsInfo piatsInfo : piatsInfos2) {
                        if (scanResult_1.equals(piatsInfo.getCode())) {//说明订单有该疫苗
                            piatsInfo.setStorageName(application.getStorageName());
                            piatsInfo.setStorageId(application.getStorageId());
                            sPiatsInfo = piatsInfo;

                        }
                    }
                    if (sPiatsInfo.getCode() == null) {//说明订单里没有这个数据
                        Toast.makeText(context, "该单号中不存在该疫苗!", Toast.LENGTH_SHORT).show();
                    } else {
                        if (VaccineContain.isContain(piatsInfos,sPiatsInfo)) {//已经扫描过
                            Toast.makeText(context, "该疫苗已经扫入!", Toast.LENGTH_SHORT).show();
                        } else {
                            piatsInfos.add(sPiatsInfo);
                            if (recyclerAdapter == null) {
                                recyclerAdapter = new RecyclerAdapter(piatsInfos);
                                rvVaccine.setAdapter(recyclerAdapter);
                            } else {
                                recyclerAdapter.notifyItemInserted(piatsInfos.size() - 1);
                                recyclerAdapter.notifyItemRangeChanged(piatsInfos.size() - 1, 1);//更新的位置,更新的总条数
                            }
                        }
                    }

                }
            }
        }
    }

    /*重写返回键*/
    private void back() {
        if (vp.getCurrentItem() == 0) {
            onBackPressed();
        } else if (vp.getCurrentItem() == 1) {
            vp.setCurrentItem(0);//如果是在内容界面点击返回,就回到单据界面
        }
    }

    /*头部的方法,因为返回的功能要重新编写,所以直接重写*/
    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    /*重写返回方法,和initHeader一样*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void saveSaleReturnMstAndDtlForPDA(String type) {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        PurchaseReceiptMstVo purchaseReceiptMstVo = new PurchaseReceiptMstVo();
        purchaseReceiptMstVo.setApprovalId(application.getApprovalId());
        purchaseReceiptMstVo.setArrivalTime(getDate(application.getArrivalTime()));
        purchaseReceiptMstVo.setCategory(piatsInfos.get(0).getCategory());
        if(application.getColdChainType()!=null){//冷链类型
            int coldChainType = Integer.valueOf(application.getColdChainType());
            if (coldChainType > 10) {//小于10的时候,在前面补0
                purchaseReceiptMstVo.setColdChainType(application.getColdChainType());
            } else {
                purchaseReceiptMstVo.setColdChainType("0" + application.getColdChainType());
            }
        }
        purchaseReceiptMstVo.setDeptId(application.getDeptId());
        purchaseReceiptMstVo.setPriceBookNo(application.getPriceNoIn());
        purchaseReceiptMstVo.setPriceBookMstId(application.getPriceBookMstId());
        purchaseReceiptMstVo.setHandleDate(getTime(new Date()));
        purchaseReceiptMstVo.setHandlerName(application.getUserName());
        purchaseReceiptMstVo.setPurchaseReturnOrderNo(application.getOrderNoName());
        purchaseReceiptMstVo.setPurchaseType("3");
        purchaseReceiptMstVo.setRunTime(getDate(application.getRunTime()));//
        purchaseReceiptMstVo.setSourceId(piatsInfos.get(0).getPurchaseReturnMstId());//退货单单号
        purchaseReceiptMstVo.setTransformUnit(application.getTransformId());
        purchaseReceiptMstVo.setTransformUnitName(application.getTransformName());
        purchaseReceiptMstVo.setSupplyDeptId(application.getSupplyDeptId());
        purchaseReceiptMstVo.setSupplyDeptName(application.getSupplyDeptName());
        if (application.getRemark() == null) {
            purchaseReceiptMstVo.setRemark("");//备注
        } else {
            purchaseReceiptMstVo.setRemark(application.getRemark());//备注
        }
        //sourceType为0代表来源类型是自制单据,3为上级退货单
        List<PurchaseReceiptDtlVo> purchaseReceiptDtlVoList = new ArrayList<PurchaseReceiptDtlVo>();
        for (int i = 0; i < piatsInfos.size(); i++) {
            PurchaseReceiptDtlVo purchaseReceiptDtlVo = new PurchaseReceiptDtlVo();
            purchaseReceiptDtlVo.setCategory(piatsInfos.get(i).getCategory());
            purchaseReceiptDtlVo.setContractNo(application.getOrderNoName());
            purchaseReceiptDtlVo.setExpiryDate(piatsInfos.get(i).getExpireDate());
            purchaseReceiptDtlVo.setIsThirdParty("1");//先默认没有第三方
            purchaseReceiptDtlVo.setLotNumber(piatsInfos.get(i).getBatchNo());
            purchaseReceiptDtlVo.setManufacturerId(piatsInfos.get(i).getProduceMappingId());
            purchaseReceiptDtlVo.setManufacturerName(piatsInfos.get(i).getProduceName());
            purchaseReceiptDtlVo.setPropertyId(piatsInfos.get(i).getPropertyId());
            purchaseReceiptDtlVo.setQuantity(String.valueOf(piatsInfos.get(i).getPkgAmount()));
            purchaseReceiptDtlVo.setServicePrice(piatsInfos.get(i).getServicePrice());
            purchaseReceiptDtlVo.setStorage(piatsInfos.get(i).getStorageName());
            purchaseReceiptDtlVo.setStorageId(piatsInfos.get(i).getStorageId());
            purchaseReceiptDtlVo.setUnitPrice(piatsInfos.get(i).getUnitPrice());
            purchaseReceiptDtlVo.setVaccineId(piatsInfos.get(i).getMappingId());
            purchaseReceiptDtlVo.setVaccineName(piatsInfos.get(i).getPhysicName());
            purchaseReceiptDtlVo.setVaccineLotsId(piatsInfos.get(i).getBatchId());
            purchaseReceiptDtlVo.setVaccineSpec(piatsInfos.get(i).getPkgSpec());
            purchaseReceiptDtlVo.setVaccineDose(piatsInfos.get(i).getPrepnSpec());
            purchaseReceiptDtlVo.setPkgAmount(Integer.parseInt(piatsInfos.get(i).getPkgAmount()));
            ElectCodePackageVoList electCodePackageVoList = new ElectCodePackageVoList();
            electCodePackageVoList.setCodeLevel(piatsInfos.get(i).getCodeLevel());
            electCodePackageVoList.setElectCode(piatsInfos.get(i).getCode());
            electCodePackageVoList.setQuantity(piatsInfos.get(i).getPkgAmount());
            purchaseReceiptDtlVo.setElectCodePackageVoList(electCodePackageVoList);
            purchaseReceiptDtlVoList.add(purchaseReceiptDtlVo);
        }
//        params.put("type", "04");//退货入库
        params.put("deptId", application.getDeptId());
        params.put("userId", application.getUserId());
        params.put("saleReturnDtlVoList", purchaseReceiptDtlVoList);
        params.put("saleReturnMstVo", purchaseReceiptMstVo);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.saveSaleReturnMstAndDtlForPDA(token, requestBody);
        jsonForResultCall.enqueue(new saveSaleReturnMstAndDtlForPDA());
    }

    private class saveSaleReturnMstAndDtlForPDA implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    Toast.makeText(context, "退货入库成功", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }
    private void orderNoSelector() {
        category.clear();
        orderNo.clear();
        id.clear();
        deptId.clear();
        sourceId.clear();
        transformUnit.clear();
        transformUnitName.clear();createTime.clear();
        for (int i = 0; i < purchaseReturnList.size(); i++) {
            orderNo.add(purchaseReturnList.get(i).getOrderNo());
            category.add(purchaseReturnList.get(i).getCategory());
            id.add(purchaseReturnList.get(i).getId());
            deptId.add(purchaseReturnList.get(i).getDeptId());
            sourceId.add(purchaseReturnList.get(i).getSourceId());
            createTime.add(purchaseReturnList.get(i).getRunTime());
            transformUnit.add(purchaseReturnList.get(i).getTransformUnit());
            transformUnitName.add(purchaseReturnList.get(i).getTransformUnitName());
        }
        showOrder();
    }

    /*button的点击监听*/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStartTime:
                getTimeDialog(v,0);
                break;
            case R.id.btnEndTime:
                getTimeDialog(v,1);
                break;
            case R.id.btnTransportEquip://下拉选择运输设备
                name.clear();id.clear();
                if(globalDictionaryList!=null){
                    for (GlobalDictionary globalDictionary : globalDictionaryList) {
                        name.add(globalDictionary.getValue());
                        id.add(globalDictionary.getKey());
                    }
                }else{
                    Toast.makeText(context,"没有获取到运输设备列表!",Toast.LENGTH_SHORT).show();
                }
                showChoose(btnTransportEquip,name,id,1);
                break;
            case R.id.btnOrderNo:
                if(purchaseReturnList!=null){
                    orderNoSelector();
                }else{
                    Toast.makeText(context,"未获取退单号,请稍后再试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSourceType:
                deptId.clear();
                deptName.clear();
                category.clear();
//                show(btnSourceType, Arrays.asList(sourceTypeName), Arrays.asList(sourceTypeId), deptId, deptName, category);
                break;
            case R.id.btnStorage:
                name.clear();
                id.clear();
                if(storageInfoList!=null){
                    for (int i = 0; i < storageInfoList.size(); i++) {
                        name.add(storageInfoList.get(i).getName());
                        id.add(storageInfoList.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 4);
                }else{
                    Toast.makeText(context,"未获取储位信息,请稍后再试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnToTemp:
                vp.setCurrentItem(1);
                break;
            case R.id.btnApprovalIn://bill界面点击选择审批人
                name.clear();
                id.clear();
                if(approvalList!=null){
                    for (int i = 0; i < approvalList.size(); i++) {
                        name.add(approvalList.get(i).getUserName1());
                        id.add(approvalList.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 0);
                }else{
                    Toast.makeText(context,"未获取审批人信息,请稍后再试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnVaccineType://bill界面点击选择疫苗类型btnVaccineType
                List<String> categoryNames = Arrays.asList(categoryName);
                List<String> categoryIds = Arrays.asList(categoryId);
                PopWindow.show(application, context,popup,isCheck, (TextView) v, categoryNames, categoryIds, 2);
                break;
            case R.id.btnPriceBook://bill界面点击选择价格本
                name.clear();
                id.clear();
                if(priceBook!=null){
                    for (int i = 0; i < priceBook.size(); i++) {
                        name.add(priceBook.get(i).getPriceBookNo());
                        id.add(priceBook.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 3);
                }else{
                    Toast.makeText(context,"未获取价格本信息,请稍后再试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSubmitVaccine://content界面点击保存扫描疫苗
                showDialog(1, v, "确认提交");
                break;
            case R.id.btnDelAllVaccine://content界面点击删除所有扫到的疫苗
                showDialog(2, v, "清空扫描");
                break;
            case R.id.btnCountVaccine://content界面点击跳转到汇总界面
                Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
                sendBroadcast(stopIntent);
                if(btnSourceType.getText().toString().equals("下级退货单")){
                    startActivity(new Intent(context,ReturnInDetailActivity.class));
                }else if(btnSourceType.getText().toString().equals("自制单据")){
                    Intent intent=new Intent(context, DetailActivity.class);
                    intent.putExtra("isOut","0");
                    startActivity(intent);
                }
                break;
        }
    }

    /*获取订单列表*/
    private void getSubordinatePurchaseReturnList() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getSubordinatePurchaseReturnList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        purchaseReturnList = JSON.parseArray(jsonForResult.getData().toString(), PurchaseReturn.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    /*根据单号id,获取单号包含疫苗列表*/
    private void getPurchaseReturnDtlByMstId(String id) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("id", id);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getPurchaseReturnDtlByMstId(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        List<DeliveryDtl> deliveryDtls = JSON.parseArray(jsonForResult.getData().toString(), DeliveryDtl.class);
                        piatsInfos2.clear();
                        for (DeliveryDtl deliveryDtl : deliveryDtls) {
                            for (ElectCodePackageVo electCodePackageVo : deliveryDtl.getElectCodePackageVoList()) {
                                PiatsInfo piatsInfo = new PiatsInfo();
                                piatsInfo.setPropertyId(deliveryDtl.getPropertyId());
                                piatsInfo.setCategory(deliveryDtl.getCategory());
                                piatsInfo.setMappingId(deliveryDtl.getVaccineId());
                                piatsInfo.setPhysicName(deliveryDtl.getVaccineName());
                                piatsInfo.setBatchId(deliveryDtl.getVaccineLotsId());
                                piatsInfo.setBatchNo(deliveryDtl.getLotNumber());
                                piatsInfo.setProduceMappingId(deliveryDtl.getManufacturerId());
                                piatsInfo.setProduceName(deliveryDtl.getManufacturerName());
                                piatsInfo.setPkgSpec(deliveryDtl.getVaccineSpec());
                                piatsInfo.setPrepnSpec(deliveryDtl.getVaccineDose());
                                piatsInfo.setUnitPrice(deliveryDtl.getUnitPrice());
                                piatsInfo.setServicePrice(deliveryDtl.getServicePrice());
                                piatsInfo.setStorageName(application.getStorageName());
                                piatsInfo.setStorageId(application.getStorageId());
                                piatsInfo.setExpireDate(deliveryDtl.getExpiryDate());
                                piatsInfo.setCodeLevel(electCodePackageVo.getCodeLevel());
                                piatsInfo.setCode(electCodePackageVo.getElectCode());
                                piatsInfo.setPkgAmount(String.valueOf(electCodePackageVo.getQuantity()));
                                piatsInfo.setPurchaseReturnMstId(deliveryDtl.getPurchaseReturnMstId());
                                piatsInfos2.add(piatsInfo);
                            }
                        }
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public void showDialog(int dex, View v, String title) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        alertBuilder.setTitle(title);
        if (title.equals("确认提交")) {
            String msg = "";
            vaccineCountList.clear();
            for (PiatsInfo piatsInfo : piatsInfos) {
                VaccineCount vaccineCount = new VaccineCount();
                vaccineCount.setName(piatsInfo.getPhysicName());
                if (!vaccineCountList.contains(vaccineCount)) {
                    vaccineCountList.add(vaccineCount);
                }
            }
            for (VaccineCount vaccineCount : vaccineCountList) {
                int num = 0;
                for (PiatsInfo piatsInfo : piatsInfos) {
                    if (piatsInfo.getPhysicName().equals(vaccineCount.getName())) {
                        num = num + Integer.valueOf(piatsInfo.getPkgAmount());
                    }
                }
                vaccineCount.setNum(num);
            }
            for (int i = 0; i < vaccineCountList.size(); i++) {
                msg = msg + "疫苗名称:" + vaccineCountList.get(i).getName() + " 扫码数:" + vaccineCountList.get(i).getNum() + "\n";
            }
            alertBuilder.setMessage("已扫疫苗 " + msg + "你确定保存吗?");
        } else if (title.equals("清空扫描")) {
            alertBuilder.setIcon(R.mipmap.dialog_alert);
            alertBuilder.setMessage("你确定清空所有扫描疫苗吗");
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (dex == 1) {//保存所有数据
                    if (btnSourceType.getText().toString().equals("自制单据")) {
                        saveSaleReturnMstAndDtlForPDA("0");
                    } else if (btnSourceType.getText().toString().equals("下级退货单")) {
                        saveSaleReturnMstAndDtlForPDA("3");
                    }
                } else if (dex == 2) {//清空储位数据
                    piatsInfos.clear();
                    RecyclerAdapter recyclerAdapter = new RecyclerAdapter(piatsInfos);
                    rvVaccine.setAdapter(recyclerAdapter);
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }
    /*选择单号下拉框*/
    private void showOrder() {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter());
        popup = new PopupWindow(context);
        popup.setWidth(btnOrderNo.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(btnOrderNo, 0, 5);//显示在edit控件的下面0,0代表偏移量
        btnOrderNo.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                btnOrderNo.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return orderNo.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            if (btnOrderNo.getText().toString().equals(orderNo.get(position))) {
                holderView.text.setTextColor(getResources().getColor(R.color.billChoosed));
            } else {
                holderView.text.setTextColor(getResources().getColor(R.color.billTextChoose));
            }
            holderView.text.setText(orderNo.get(position));
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getPurchaseReturnDtlByMstId(id.get(position));
                    btnOrderNo.setText(orderNo.get(position));
                    btnOrderNo.setTextColor(getResources().getColor(R.color.billTextChoose));
                    application.setOrderNoId(id.get(position));
                    application.setOrderNoName(orderNo.get(position));
                    btnOrderNo.setBackgroundResource(R.drawable.selector_unfocused);
                    btnOutDept.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnVaccineType.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnStartTime.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnEndTime.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnEndTime.setText(getTime(new Date()));
                    btnStartTime.setText(createTime.get(position));
                    if(!StringUtil.isNullOrEmpty(transformUnit.get(position))&&!StringUtil.isNullOrEmpty(transformUnitName.get(position))){
                        application.setTransformId(transformUnit.get(position));
                        application.setTransformName(transformUnitName.get(position));
                        btnDeliveryDept.setText(transformUnitName.get(position));
                    }else{
                        application.setTransformId(null);
                        application.setTransformName(null);
                        btnDeliveryDept.setText("");
                    }

                    for (int m = 0; m < deptList.size(); m++) {
                        if (deptList.get(m).getRefDeptId().equals(deptId.get(position))) {
                            isCheck=true;
                            application.setSupplyDeptName(deptList.get(m).getName());
                            application.setSupplyDeptId(deptList.get(m).getId());
                            btnOutDept.setText(deptList.get(m).getName());
                            break;
                        }
                    }
                    for (int n = 0; n < approvalList.size(); n++) {
                        if (approvalList.get(n).getIsDefault()) {
                            application.setApprovalId(approvalList.get(n).getId());
                        }
                    }
                    application.setVaccineType(category.get(position));
                    if (category.get(position).equals("1")) {
                        btnVaccineType.setText("免疫规划");
                    } else if (category.get(position).equals("2")) {
                        btnVaccineType.setText("非免疫规划");
                    } else if (category.get(position).equals("3")) {
                        btnVaccineType.setText("配套品");
                    }
                    application.setSourceId(sourceId.get(position));
                    application.setVaccineType(category.get(position));
                    application.setRunTime(btnStartTime.getText().toString());
                    application.setArrivalTime(btnEndTime.getText().toString());
                    notifyDataSetChanged();
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }
    class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeScan(context);
        piatsInfos.clear();
        application.clearBill();//将bill里的数据清除
    }
}